<template>
 <div class="e-form">
    <div class="tabs warningTabs
    ">
        <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
            <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag">
            </el-tab-pane>

            <div>
                <!-- 基本信息 -->
                <div id="baseInfoCon" class="con">
                    <div class="tabs-title" id="baseInfo">基本信息</div>
                   <div style="width: 100%" class="form">
                    <el-form :model="formData" :label-width="formLabelWidth" :rules="rulesBase" ref="rulesBase" class="demo-ruleForm">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="合同编号：">
                                    <span>{{formData.contractNumber}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属机构：">
                                    <span>{{ formData.orgName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="合同名称：">
                                    <span>{{formData.contractName}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="合同类型：">
                                    <span>物资采购合同</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="不含税金额(元)：">
                                    <span>{{
                                        formData.taxExcludedAmount
                                    }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="合同金额(元)：">
                                    <span>{{
                                        formData.contractAmount
                                    }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="12">
                                <el-form-item label="终止日期：" prop="stopDate">
                                    <span>{{
                                        formData.stopDate
                                    }}</span>
                                </el-form-item>
                            </el-col>
                             <el-col :span="12">
                                <el-form-item label="已结算金额：">
                                   <span>{{formData.serverUnitAmount}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="终止原因：" prop="stopReason">
                                    <span>{{
                                        formData.stopReason
                                    }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                         <el-row>
                            <el-col :span="12">
                                <el-form-item label="经办人：">
                                    <span>{{userInfo.userName}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="录入日期：">
                                    <span>{{formData.gmtCreate}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="状态：">
                                    <span>{{state.find(x=>x.value === formData.state).label}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="formData.state === 5">
                            <el-col :span="12">
                                <el-col :span="12">
                                    <el-form-item label="作废人：">
                                        <span>{{ formData.nullifyCreator }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="作废时间：">
                                    <span>{{ formData.nullifyCreated }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="formData.state === 5">
                            <el-col :span="12">
                                <el-col :span="12">
                                    <el-form-item label="作废原因：">
                                        <span>{{ formData.nullifyReason }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="作废说明：">
                                    <span>{{ formData.nullifyDescription }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                </div>

                <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="subcontract"
                            isView
                        />
                    </div>

                <!-- 审核历史 -->
                <div id="auditHistoryCon" class="con">
                    <div class="tabs-title" id="auditHistory">审核历史</div>
                    <AuditHistoryIndex :billType="7028"></AuditHistoryIndex>
                </div>
            </div>
        </el-tabs>
    </div>
    <div class="buttons">
        <ComExaButtons :auditState="auditState" :state="formData.state" @exas="exas" :founderId="formData.founderId" />
        <el-button size="small" @click="handleClose">取消</el-button>
    </div>
    <div id="seat" :style="{height: seatHeight + 'px'}"></div>
 </div>
</template>
<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import fn from '@/utils/checkEmpty.js'
import AttachComp from '@/components/common/attachIndex'
import ComExaButtons from '@/components/common/exaButtons'
import endContract from '@/api/balanceContractApi/ctMaterialPurchaseApi/endContract.js'
import auditRequest from '@/api/subcontractApi/audit.js'
import $ from 'jquery'
import { showLoading, hideLoading, formatDate, throttle  } from '@/utils/common'
import AuditHistoryIndex from '@/pages/subcontract/components/auditHistory/auditHistoryIndex.vue'
import { exas, saveAll, submitCommit } from '@/pages/subcontract/common/contractCom.js'
export default {
    data () {
        return {
            //基本信息表单数据
            formData: {
                address: '',
                advanceCharge: null,
                advanceChargeProportion: null,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: null,
                billId: '',
                bondAmount: null,
                bondState: null,
                contractAmount: null,
                contractContext: '',
                contractName: '',
                contractNumber: '',
                contractState: null,
                contractType: null,
                contractTypeName: '',
                currencyId: '',
                currencyName: '',
                financialSharing: null,
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                nailDetailedListState: null,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                period: null,
                rmbName: '',
                rmbRate: null,
                signingDate: '',
                signingEndTime: '',
                signingId: '',
                signingName: '',
                signingStartTime: '',
                state: null,
                taxAmount: null,
                taxExcludedAmount: null,
                taxRate: null,
                workId: ''
            },
            //主体信息表单数据
            mainInfo: {
                firstParty: {
                    accountNumber: '',
                    address: '',
                    bankName: '',
                    billId: '',
                    fax: '',
                    legalRepresentative: '',
                    orgId: '',
                    orgName: '',
                    phone: '',
                    postalCode: '',
                    principalAgent: '',
                    sourceId: ''
                },
                notarization: {
                    accountNumber: '',
                    bankName: '',
                    billId: '',
                    name: '',
                    notaryTime: '',
                    opinion: '',
                    sourceId: this.$route.query.billid
                },
                secondParty: {
                    'accountNumber': '',
                    'address': '',
                    'bankName': '',
                    'biddingId': '',
                    'biddingName': '',
                    'billId': '',
                    'dtlId': '',
                    'fax': '',
                    'id': '',
                    'legalRepresentative': '',
                    'name': '',
                    'phone': '',
                    'postalCode': '',
                    'principalAgent': '',
                    'socialCode': '',
                    sourceId: this.$route.query.billid
                }
            },
            formLabelWidth: '195px',
            ctsubcontractId: '', //合同id
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
 	        winEvent: {},
            errorList: [], //控制导航栏感叹号的显示
            contractListTable: [], //合同清单表格数据
            goodsListTable: [], //物资清单表格数据
            equipListTable: [], //设备清单表格数据
            deviceListTable: [], //设备清单表格数据
            earnestMoneyTable: [], //保证金表格数据
            commonCtTermsTable: [], //通用合同条款表格数据
            onlyCtTermsTable: [], //项目专用合同条款表格数据
            attachTable: [], //附件信息表格数据
            auditHistoryTable: [], //审核历史表格数据
            signLogTable: [], //签订记录表格数据
            changeLogTable: [], //变更历史表格数据
            settlementParameterTable: [], //结算台账表格数据
            terminationLogTable: [], //终止记录表格数据
            objFlag: {
                //判断是否转圈圈
                flag1: false,
                flag2: false,
                flag3: false,
                flag4: false,
                flag5: false,
                flag6: false,
                flag7: false,
                flag8: false,
                flag9: false,
                flag10: false,
                flag11: false,
                flag12: false
            },
            billid: this.$route.query.billid,
            rulesBase: {
                stopReason: [
                    { required: true, message: '请输入终止原因', trigger: 'blur' },
                    { min: 1, max: 500, message: '最多输入500字', trigger: 'blur' }
                ],
                stopDate: [
                    { required: true, message: '请选择终止日期', trigger: 'change' },
                    { validator: (rule, value, callback)=>{
                        const singTime = new Date(this.formData.stopDate).getTime() //终止日期
                        const startTime = new Date(formatDate(new Date(), 'yyyy-MM-dd')).getTime() //当前时间
                        if(singTime > startTime) {
                            callback(new Error('终止日期不能大于当前日期'))
                        }else{
                            callback()
                        }

                    }, trigger: 'change' }
                ],
            },
            disabled: false, //是否禁止
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 7028
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 7028,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            isContructSearchKey: false,
            errorContractMsg: [],
            TreeContractListShow: true,
            MaterialListShow: true,
            isMonitorTaxRate: false, //是否计算税率
            subcontract: null, //当前页面的api
        }
    },
    components: {
        AttachComp,
        AuditHistoryIndex,
        ComExaButtons
    },
    created () {
        this.init()
        this.subcontract = endContract

    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'attach',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
        if(this.$route.query.name) {
            setTimeout(()=>{
                this.onChangeTab({
                    name: this.$route.query.name
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            financialSharingList: state => state.contract.ctClassify.financialSharingList, //传输财务共享
            state: state => state.equip.equipData.state, //通用流程状态
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
        //是否是从招标引入 true招标false目标预算
        isBidding () {
            return this.mainInfo.secondParty.biddingId ? true : false
        },
        showAddress () {
            return value=>{
                const obj = JSON.parse(value)
                const  address = obj.address ? obj.address.join('-') : ''
                const  detail = obj.detail
                let str = ''
                if(address && detail) {
                    str = address + '-' + detail
                }else if(!address  && detail) {
                    str = detail
                }else if(address  && !detail) {
                    str = address
                }
                return str
            }
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        ...mapMutations(['setSelectedInfo']),
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getBasic(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            if(this.formData.state !== -1 && this.formData.state !== 2 && this.formData.state !== 5) {
                auditRequest.getUnitInfoByBillId(this.auditParams).then(res => {
                    this.auditState = res
                })
            }
        },
        //取消
        handleClose () {
            hideLoading()
            this.$router.replace('/ctMaterialPurchaseHV')
        },
        //判断数据是否为空
        checkEmpty (datas) {
            return fn.checkEmpty(datas)
        },
        //根据id查询基础信息
        getBasic () {
            this.isMonitorTaxRate = false
            endContract.getInfo(this.billid).then(res => {
                this.formData = res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.rulesBase.validate(valid => {
                    if (valid) {
                        endContract.createInfo(this.formData).then(() => {
                            this.clearError('baseInfo')
                            resolve()
                            this.getBasic()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })

        },
        //删除基本信息
        deleteBaseInfo () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    showLoading()
                    endContract.deleteInfo(this.billid).then(() => {
                        hideLoading()
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                ]
            }
            submitCommit(this, requestFn)
        },
        //保存
        submit () {
            this.saveAll()
        },
        //删除所有信息
        deleteData () {
            this.deleteBaseInfo()
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            exas(arg, this, requestFn)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistory')) {
                    const lastConHeight =
                        document.getElementById('auditHistory').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.mainTitle {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246, 246, 246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}

</style>

